/*
 * @Author: 晴鸢. 3013433857@qq.com
 * @Date: 2025-08-31 10:49:16
 * @LastEditors: 晴鸢. 3013433857@qq.com
 * @LastEditTime: 2025-08-31 16:14:58
 * @FilePath: /Learn/sharemem/common.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
 #pragma once
 #include<iostream>
 #include<string>
 #include<string.h>
 #include<sys/ipc.h>
 #include<sys/shm.h>
 #include<sys/types.h>
 #include<sys/stat.h>
 #include"log.hpp"
 using namespace std;
const string pathname="/home/performer";
const int size=1024*4;//4kb  一般是4096的整数倍
const int proj_id=0x6666;
Log log;
key_t Getkey()
{
    key_t k=ftok(pathname.c_str(),proj_id);//key本质是int
    if(k<0)
    {
        log(Fatal,"ftok error:%s\n",strerror(errno));
        perror("ftok error");
        exit(1);
    }
    log(Info,"ftok success,key is 0x%x\n",k);
    return k;
}

//flag为控制权限的选项
int Getsharemem(int flag)
{
    key_t key=Getkey();
    int shmid=shmget(key,size,flag);
    if(shmid<0)
    {
        log(Fatal,"create shared memory error:%s\n",strerror(errno));
        exit(2);
    }
    log(Info,"create shared memory success,shmid:%d\n",shmid);
    return shmid;
}

//创建共享内存
int CreateShm()
{
    return Getsharemem(IPC_CREAT|IPC_EXCL|0666);
}

//获取共享内存
int GetShm()
{
    return Getsharemem(IPC_CREAT);
}

#define FIFO_FILE "./myfifo" //文件路径+名称
#define MODE 0664 //文件权限

enum{
    FIFO_CREATE_ERR=1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};


class Init
{
public:
    Init()
    {
         //创建管道
        int n=mkfifo(FIFO_FILE,MODE);
        if(n==-1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }

    ~Init()
    {
         int m=unlink(FIFO_FILE);
        if(m==-1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};
